from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
from io import BytesIO

def check_code(size=(200, 80), chars=4):
    # 生成随机字符（数字+大小写字母）
    captcha_text = ''.join(random.choices(
        string.ascii_letters + string.digits, k=chars))
    
    # 创建图像对象
    image = Image.new('RGB', size, (255, 255, 255))
    draw = ImageDraw.Draw(image)
    
    # 加载字体（需自行准备字体文件或使用系统默认）
    try:
        font = ImageFont.truetype('arial.ttf', 40)
    except:
        font = ImageFont.load_default().font_variant(size=36)
    
    # 绘制随机扭曲的字符
    for i, char in enumerate(captcha_text):
        # 随机位置和角度
        x = 20 + i * 40 + random.randint(-5, 5)
        y = random.randint(10, 30)
        angle = random.randint(-30, 30)
        
        # 绘制字符
        draw.text((x, y), char, 
                 fill=(random.randint(0, 150), 
                       random.randint(0, 150), 
                       random.randint(0, 150)),
                 font=font,
                 angle=angle)
    
    # 添加干扰元素
    # 1. 随机噪点
    for _ in range(int(size[0]*size[1]*0.15)):
        draw.point((random.randint(0, size[0]), 
                   random.randint(0, size[1])),
                  fill=(random.randint(0, 255), 
                        random.randint(0, 255), 
                        random.randint(0, 255)))
    
    # 2. 干扰线
    for _ in range(3):
        start = (random.randint(0, size[0]), random.randint(0, size[1]))
        end = (random.randint(0, size[0]), random.randint(0, size[1]))
        draw.line([start, end], 
                 fill=(random.randint(0, 255), 
                       random.randint(0, 255), 
                       random.randint(0, 255)),
                 width=1)
    
    # 模糊处理（可选）
    image = image.filter(ImageFilter.CONTOUR)
    #下面返回图片对象和字符
    return image,captcha_text
    
